<template>
  <div>
    <a-row>
      <a-col :offset="6" :span="12">
        <a-card :title="title">
          <a-form v-bind="layout">
            <a-form-item label="名称" required="true" v-bind="validateInfos.name">
              <a-input v-model:value="productParam.name" />
            </a-form-item>
            <a-form-item label="选择分类" required="true" v-bind="validateInfos.categoryId">
              <category-selection
                ref="csRef"
                :value="productParam.categoryId"
                @categorySelected="doCategorySelected"
              />
            </a-form-item>

            <a-form-item label="选择品牌" v-bind="validateInfos.brandId">
              <brand-selection
                ref="bsRef"
                :value="productParam.brandId"
                @brandSelected="doBrandSelected"
              />
            </a-form-item>

            <a-form-item label="选择主单位" v-bind="validateInfos.unitId">
              <unit-selection
                ref="usRef"
                :value="productParam.unitId"
                @unitSelected="doUnitSelected"
              />
            </a-form-item>

            <a-form-item label="描述" v-bind="validateInfos.description">
              <a-input v-model:value="productParam.description" />
            </a-form-item>
            <a-form-item :wrapper-col="{ span: 14, offset: 8 }">
              <a-button v-if="isEdit" type="primary" @click="update">修改</a-button>
              <a-button v-else type="primary" @click="add">确定</a-button>
              <a-button style="margin-left: 30px" @click="resetFields">重置</a-button>
            </a-form-item>
          </a-form>
          <template v-if="isEdit">
            <a-divider />
            <a-tabs>
              <a-tab-pane key="2" tab="单位">
                <a-row>
                  <a-col :span="8" :offset="16" style="text-align: right">
                    <a-space
                      ><a-button type="link" @click="showUnitEditor">添加单位</a-button
                      ><a-button type="link" @click="removeUnit">删除</a-button></a-space
                    ></a-col
                  >
                </a-row>
                <a-table
                  :columns="unitColumns"
                  :data-source="productUnitDataSet"
                  :pagination="false"
                  :row-selection="rowSelection"
                  rowKey="uid"
                >
                  <template #primary="{ text, record }">
                    <span v-if="record.isPrimary">是</span>
                    <span v-else>否</span>
                  </template>
                </a-table>
              </a-tab-pane>
            </a-tabs>
          </template>
        </a-card>
        <a-modal v-model:visible="editorVisible" title="选择单位" centered @ok="newUnitConfirmed">
          <a-table
            :data-source="filteredUnitDataSet"
            :columns="unitAddColumns"
            :row-selection="unitRowSelection"
            row-key="uid"
          />
        </a-modal>
      </a-col>
    </a-row>
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, reactive, ref } from 'vue'
import { useHttpRequest } from '@/api/chunfeng/apiRequest'

import CategorySelection from '@/components/chunfeng/category/CategorySelection.vue'

import { useProductApi } from '@/api/chunfeng/product'
import {
  AddProductData,
  ProductData,
  ProductUnitData,
  ProductParam,
} from '@/api/chunfeng/product/interfaces'
import BrandSelection from '@/components/chunfeng/brand/BrandSelection.vue'
import UnitSelection from '@/components/chunfeng/unit/UnitSelection.vue'
import { useRoute } from 'vue-router'
import { UnitData } from '@/api/chunfeng/unit/interfaces'
import { useUnitApi } from '@/api/chunfeng/unit'
import { Form } from 'ant-design-vue'

export default defineComponent({
  name: 'ProductEditor',
  components: { UnitSelection, BrandSelection, CategorySelection },
  props: {
    isEdit: {
      type: Boolean,
      required: false,
      default: false,
    },
  },

  setup(props, context) {
    const { executeCommandRequest, executeQueryRequest } = useHttpRequest()
    const csRef = ref()
    const bsRef = ref()
    const usRef = ref()
    const productUnitDataSet = ref(Array<ProductUnitData>())

    const editorVisible = ref(false)

    const filteredUnitDataSet = reactive<Array<UnitData>>([])

    const {
      addProduct,
      queryProductUnit,
      getProductById,
      addProductUnit,
      removeProductUnit,
      updateProduct,
    } = useProductApi()

    const productParam = reactive<ProductParam>({
      uid: '',
      name: '',
      categoryId: '',
      brandId: '',
      unitId: '',
      description: undefined,
    })
    let uid = ''

    const title = ref('新增商品')
    if (props.isEdit) {
      title.value = '修改商品'

      const route = useRoute()

      const productId = route.query.productId
      if (typeof productId === 'string') {
        uid = productId
        executeQueryRequest(getProductById(productId), (data: ProductData) => {
          productParam.uid = uid
          productParam.name = data.name
          productParam.brandId = data.brand.uid
          productParam.categoryId = data.category.uid
          productParam.unitId = data.primaryUnit.uid
          productParam.description = data.description
        })

        loadProductUnit(productId)
      }
    }

    const unitColumns = [
      {
        title: '单位名称',
        dataIndex: 'unit.name',
        key: 'unitName',
      },
      {
        title: '是否主单位',
        dataIndex: 'isPrimary',
        key: 'primary',
        slots: { customRender: 'primary' },
      },
    ]

    const unitAddColumns = [
      {
        title: '单位名称',
        dataIndex: 'name',
        key: 'name',
      },
    ]

    const rules = reactive({
      uid: [
        {
          required: false,
        },
      ],
      name: [
        {
          required: true,
          message: '请输入商品名称',
        },
      ],
      categoryId: [
        {
          required: true,
          message: '请选择商品分类',
        },
      ],
      brandId: [
        {
          required: true,
          message: '请选择品牌',
        },
      ],
      unitId: [
        {
          required: true,
          message: '请选择主单位',
        },
      ],
      description: [
        {
          required: false,
        },
      ],
    })

    const { resetFields, validate, validateInfos } = Form.useForm(productParam, rules)
    const layout = {
      labelCol: { span: 5 },
      wrapperCol: { span: 14 },
    }

    function update() {
      validate().then((data) => {
        executeCommandRequest(updateProduct(data), {
          message: '修改商品成功',
          callback: () => {},
        })
      })
    }

    function add() {
      validate<AddProductData>().then((data) => {
        executeCommandRequest(addProduct(data), {
          message: '添加商品成功',
          callback: () => {
            resetFields()
            csRef.value.reset()
            bsRef.value.reset()
            usRef.value.reset()
          },
        })
      })
    }

    function loadProductUnit(productId: string) {
      productUnitDataSet.value.length = 0
      executeQueryRequest(queryProductUnit(productId), (data: ProductUnitData[]) => {
        productUnitDataSet.value.push(...data)
      })
    }

    function doCategorySelected(categoryId: string) {
      productParam.categoryId = categoryId
    }

    function doBrandSelected(brandId: string) {
      productParam.brandId = brandId
    }

    function doUnitSelected(unitId: string) {
      productParam.unitId = unitId
    }

    const rowSelected: string[] = []

    const rowSelection = {
      onChange: (selectedRowKeys: string[], selectedRows: ProductUnitData[]) => {
        rowSelected.length = 0
        rowSelected.push(...selectedRowKeys)
      },
      getCheckboxProps: (record: ProductUnitData) => ({
        disabled: record.isPrimary, // Column configuration not to be checked
        name: record.unit.name,
      }),
    }

    function removeUnit() {
      if (rowSelected.length > 0) {
        rowSelected
          .map((value) => ({ uid: uid, productUnitId: value }))
          .forEach((data) => {
            executeCommandRequest(removeProductUnit(data), {
              callback: () => {
                productUnitDataSet.value = productUnitDataSet.value.filter(
                  (v) => v.uid !== data.productUnitId,
                )
              },
            })
          })
      }
    }

    function showUnitEditor() {
      filteredUnitDataSet.length = 0
      const existUnitIds = productUnitDataSet.value.map((pu) => pu.unitId)
      const { queryUnit } = useUnitApi()
      executeQueryRequest(queryUnit({ enabled: true }), (data: UnitData[]) => {
        filteredUnitDataSet.push(...data)
      })

      editorVisible.value = true
    }

    function checkUnitExist(id: string): boolean {
      return productUnitDataSet.value.filter((value) => value.unitId == id).length > 0
    }

    const selectedNewUnitId: string[] = []

    function checkUnitSelect(id: string): boolean {
      console.log(`check unit selected: ${id}`)
      return selectedNewUnitId.filter((value) => value == id).length > 0
    }

    const unitRowSelection = {
      onChange: (selectedRowKeys: string[], selectedRows: UnitData[]) => {
        selectedNewUnitId.length = 0
        selectedNewUnitId.push(...selectedRowKeys)
        console.log(`selected unit ids:[${selectedRowKeys}]######[${selectedNewUnitId}]`)
      },
      getCheckboxProps: (record: UnitData) => ({
        disabled: checkUnitExist(record.uid), // Column configuration not to be checked
        name: record.name,
      }),
    }

    function newUnitConfirmed() {
      editorVisible.value = false
      const data = selectedNewUnitId.map((value) => ({
        uid: uid,
        unitId: value,
        primary: false,
      }))

      executeCommandRequest(addProductUnit(data), {
        message: '添加单位成功',
        callback: () => {},
      })
    }

    return {
      productParam,
      validateInfos,
      layout,
      add,
      resetFields,
      doCategorySelected,
      doBrandSelected,
      csRef,
      bsRef,
      usRef,
      doUnitSelected,
      unitColumns,
      productUnitDataSet,
      title,
      rowSelection,
      editorVisible,
      showUnitEditor,
      filteredUnitDataSet,
      unitAddColumns,
      unitRowSelection,
      newUnitConfirmed,
      removeUnit,
      update,
    }
  },
})
</script>
